var editRowsNumber,_datasDatagrid,selectForm,createDate1,createDate2,selectUsername,selectNickname,selectEmail,selectPhone,selectStatus;
var parentCenterTabs,dialogWeixinMaterial,formWeixinMaterial,id,created_at,media,type,title,introduction,digest,logo,sessionID;

/**新增临时素材*/
function addTemp() {
	addRow(0);
}

/**新增永久素材*/
function addPermanent() {
	addRow(1);
}

function initUploadify(midiaType, midiaStatus) {
	var fileSizeLimit = "1MB";
	var fileTypeExts = "*.gif; *.jpg; *.png;";
	var buttonText = "上传图片";
	var formData = {'sessionID':sessionID,'type':'image'};
	if (midiaType == 'image'){
		fileSizeLimit = "1MB";
		fileTypeExts = "*.gif; *.jpg; *.png;";
		formData = {'sessionID':sessionID,'type':'image'};
		buttonText = "上传图片";
		if (midiaStatus == 1) {
			formData={'sessionID':sessionID,'status':'yes','type':'image'};
		}
	} else if (midiaType == 'voice'){
		fileSizeLimit = "2MB";
		fileTypeExts = "*.mp3; *.wav;";
		formData = {'sessionID':sessionID,'type':'voice'};
		buttonText = "上传语音";
		if (midiaStatus == 1) {
			formData={'sessionID':sessionID,'status':'yes','type':'voice'};
		}
	} else if (midiaType == 'video'){
		fileSizeLimit = "10MB";
		fileTypeExts = "*.mp4; *.avi;";
		formData = {'sessionID':sessionID,'type':'video'};
		buttonText = "上传视频";
		if (midiaStatus == 1) {
			formData={'sessionID':sessionID,'status':'yes','type':'video'};
		}
	} else if (midiaType == 'thumb'){
		fileSizeLimit = "64KB";
		fileTypeExts = "*.gif; *.jpg; *.png;";
		formData = {'sessionID':sessionID,'type':'thumb'};
		buttonText = "上传缩略图";
		if (midiaStatus == 1) {
			formData={'sessionID':sessionID,'status':'yes','type':'thumb'};
		}
	}
	logo.uploadify({
		method:'post',
		swf:sy.bp() + '/resources/uploadify/uploadify.swf',
		uploader:sy.bp() + '/admin/fileUpload/weixin',
		fileObjName:'file',
		auto:true,
		buttonText:buttonText,
	    queueSizeLimit:1,
	    multi:false,
	    removeCompleted:true,
	    successTimeout:1000,
	    fileSizeLimit:fileSizeLimit,
		fileTypeExts:fileTypeExts,
		formData:formData,
	    onUploadSuccess:function(file, data, response) {
	    	var resObj = $.parseJSON(data);
	        if (resObj.result == 1) {
	        	$('#logoPic').attr('src', sy.bp() + '/resources/upload/weixin/' + resObj.obj);
	        	$('#logosrc').val(resObj.obj);
	        	$(addOrUpdate).linkbutton('enable');
	        } else {
	        	$.messager.alert('警告', data.msg, 'warning');
	        }
	    }
	});
}

function addRow(midiaStatus) {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		$('#status').val(midiaStatus);
		id.val(0);
		created_at.val('');
		media.val('');
		$('#logoPic').attr('src', sy.bp() + '/resources/css/images/logo_px.png');
		title.val('');
		introduction.val('');
		initUploadify($('#type').combobox('getValue'), midiaStatus);
		dialogWeixinMaterial.dialog({title:'添加回复消息',iconCls:'icon-add',buttons:[{id:'addOrUpdate',text:'添加',disabled:true,handler:dialogHandler}]});
		dialogWeixinMaterial.dialog('open');
	}
}

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/weixin/material/deletes", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var rowData = rows[0];
			id.val(rowData.id);
			created_at.val(rowData.created_at);
			media.val(rowData.media);
			$('#logoPic').attr('src', sy.bp() + '/resources/upload/weixin/' + rowData.media);
			type.combobox('setValue',rowData.type);
			$('#status').val(rowData.status);
			title.val(rowData.title);
			introduction.val(rowData.introduction);
			dialogWeixinMaterial.dialog({title:'更新回复消息',iconCls:'icon-add',buttons:[{id:'addOrUpdate',text:'更新',disabled:true,handler:dialogHandler}]});
			dialogWeixinMaterial.dialog('open');
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
}

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
}

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
}

function search_datas() {
	var formData = selectForm.form('getData', true);
	if(formData.createDate1 != '' && formData.createDate2 != '' && formData.createDate1 > formData.createDate2){
		$.messager.alert('提示', '开始时间不得大于结束时间，请重新选择！', 'warning');
	} else {
		if (selectForm.form('validate')) {
			_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
		}
	}
};

function dialogHandler() {
	//if (formWeixinMaterial.form('validate')) {
		$(addOrUpdate).linkbutton('disable');
		var url = sy.bp() + "/admin/weixin/material/";
		if (id.val() == '0') {
			url += "add";
		} else {
			url += "update";
		}
		$.post(url, $('#formWeixinMaterial').serialize(), function(data) {
			if (data && data.result == 1) {
				dialogWeixinMaterial.dialog('close');
				_datasDatagrid.datagrid('reload');
				$.messager.show({title:'系统提示',msg:'提交成功!',timeout:2000,showType:'slide'});
			} else {
				$.messager.alert('系统提示', data.msg);
			}
		}, "json");
	//}
}

$(function(){
	var jsonArr ;	
//	= [
//       {value:'image',text:'图片类型'},{value:'voice',text:'语音类型'},
//       {value:'video',text:'视频类型'},{value:'thumb',text:'缩略图'},
//       {value:'news',text:'图文类型'}
//    ];
	var jsonArrStatus = [{value:0,text:'临时素材'},{value:1,text:'永久素材'}];
	$('#weixinImageTextIds1').hide();
	$('.videoMaterial').hide();
	parentCenterTabs = parent.centerTabs;
	_datasDatagrid = $('#_datasDatagrid');
	editRowsNumber = -1;
	selectForm = $('#selectForm');
	id = $('#id');
	logo = $('#logo');
	sessionID = $('#sessionID').val();
	created_at = $('#created_at');
	media = $('#media');

	type = $('#type').combobox({required:true,editable:false,valueField:'code',textField:'name',
		url:sy.bp() + "/admin/dictionary/listDictionary?name=微信消息类型",
		onLoadSuccess : function(data) {
			     jsonArr = JSON.parse(JSON.stringify(data)); 
		},
		onChange:function(newValue, oldValue){
			initUploadify(newValue, $('#status').val());
			if (oldValue && newValue){
				if (newValue == 'image'){
					$('#weixinImageTextIds1').hide();
					$('#uploadMaterial').show();
					$('.videoMaterial').hide();
					$(addOrUpdate).linkbutton('disable');
				} else if (newValue == 'voice'){
					$('#weixinImageTextIds1').hide();
					$('#uploadMaterial').show();
					$('.videoMaterial').hide();
					$(addOrUpdate).linkbutton('disable');
				} else if (newValue == 'video'){
					$('#weixinImageTextIds1').hide();
					$('#uploadMaterial').show();
					if ($('#status').val() == 1) {
						$('.videoMaterial').show();
					} else {
						$('.videoMaterial').hide();
					}
					$(addOrUpdate).linkbutton('disable');
				} else if (newValue == 'thumb'){
					$('#weixinImageTextIds1').hide();
					$('#uploadMaterial').show();
					$('.videoMaterial').hide();
					$(addOrUpdate).linkbutton('disable');
				} else if (newValue == 'news'){
					$('#weixinImageTextIds1').show();
					$('#uploadMaterial').hide();
					$('.videoMaterial').hide();
					$(addOrUpdate).linkbutton('enable');
				}
			}
		}
	}).combobox('activeTextArrow').combobox('setValue', 'image');
	title = $('#title').validatebox({required:true,validType:['maxLength[20]']});
	introduction = $('#introduction').validatebox({required:true,validType:['maxLength[200]']});
	weixinImageTextIds = $('#weixinImageTextIds').combogrid({panelWidth:430,idField:'id',textField:'id',pagination:true,multiple:true,fitColumns:true,
		pageSize:10,pageList:[10,20,30,40,50],border:false,sortName:'id',sortOrder:'desc',view:sy.myview,emptyMsg:'没有查询到相关数据',
		url:sy.bp()+'/admin/weixin/imageTextMsg/list',queryParams:{isMaterial:'yes'},
		columns:[[
		  {field:'id',hidden:true},
          {field:'author',title:'作者',align:'left',width:50,sortable:true},
          {field:'digest',title:'摘要',align:'left',width:50,sortable:true},
          {field:'thumb_media_id',title:'封面素材',align:'left',width:50,sortable:true},
          {field:'show_cover_pic',title:'是否显示封面',align:'left',width:50,sortable:true},
          {field:'content',title:'内容',align:'left',width:100,sortable:true},
          {field:'content_source_url',title:'原文地址',align:'left',width:100,sortable:true}
        ]]  
	}).combogrid('activeTextArrow');
	dialogWeixinMaterial = $('#dialogWeixinMaterial').show().dialog({
		resizable : false,
		closed : true,
		closable : true,
		modal : true
	});
	formWeixinMaterial = $('#formWeixinMaterial').form({});
	
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/weixin/material/list',
		fit : true,
		autoRowHeight : false,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : false,
		border : false,
		idField : 'id',
		sortName : 'id',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
			{text:'新增临时素材',iconCls: 'icon-add',handler: addTemp},'-',
			{text:'新增永久素材',iconCls: 'icon-add',handler: addPermanent},'-',
			{text:'批量删除',iconCls: 'icon-remove',handler: deleteRow},'-',
			{text:'编辑',iconCls: 'icon-edit',handler: updateRow},'-',
			{text:'保存',iconCls: 'icon-save',handler: saveRow},'-',
			{text:'撤销',iconCls: 'icon-redo',handler: rejectRow},'-',
			{text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}}
		],
		frozenColumns: [[
            {field:'id',title:'编号',align:'center',width:100,sortable:true,checkbox:true},
		]],
		columns:[[
            {field:'status',title:'类型',align:'left',width:100,sortable:true,
	            formatter:function(value, row) {
	        		for ( var i = 0; i < jsonArrStatus.length; i++) {
						if (value == jsonArrStatus[i].value) {
							return jsonArrStatus[i].text;
						}
					}
	        	}
	        	//editor:{type:'combobox',options:{required:true,editable:false,valueField:'value',textField:'text',data:jsonArrStatus}}
            },
            {field:'type',title:'媒体类型',align:'left',width:100,sortable:true,
            	formatter:function(value, row) {
            		for ( var i = 0; i < jsonArr.length; i++) {
						if (value == jsonArr[i].code) {
							return jsonArr[i].name;
						}
					}
            	}
            	//editor:{type:'combobox',options:{required:true,editable:false,valueField:'value',textField:'text',data:jsonArr}}
	        },
	        {field:'media_id',title:'媒体ID',align:'left',width:400,sortable:true},
          	{field:'createTime',title:'上传时间',align:'left',width:100,sortable:true}
		]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
				updateRow();
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		}
	});
});